<?php
namespace app\backend\controller;

class Upload extends Backend {
	
	public function image() {
		
		$request = \think\Request::instance();
		
		// 校验文件类型
		$type = $request->post('type', '');
		$astrict = \think\Config::get('upload_image');
		if(!array_key_exists($type, $astrict)){
			return $this->disposeJson(1, '上传类型不正确');
		};
		$astrict = $astrict[$type];
		
		// 获取上传文件
		$file = $request->file('file');
		if(!is_object($file)){
			return $this->disposeJson(1, '未找到上传文件');
		};
		
		// 判断文件类型是否允许
		$info = $file->getInfo();
		$type_file = explode('/', $info['type']);
		$type_accept = explode('|', $astrict['type']);
		if(!in_array($type_file[1], $type_accept)){
			return $this->disposeJson(1, '该文件的类型不被允许');
		};
		
		// 判断文件大小
		if($astrict['size'] < ($info['size'] / 1000)){
			return $this->disposeJson(1, '该文件的体积过大');
		};
		
		// 判断目录并创建
		$dir_root = ROOT_PATH . 'public' . DS;
		$dir_path = 'resource' . DS . 'image' . DS . $type . DS;
		if(!file_exists($dir_root . $dir_path)){
			$path = $dir_root . $dir_path;
			$result = mkdir($path, 0770, true);
			if(!$result){
				return $this->disposeJson(1, '创建目录失败');
			};
		};
		
		// 重新绘图并保存
		$file_name = date('YmdHis') . rand(1000, 9999) . '.' . $type_file[1];
		$file_full = $dir_root . $dir_path . $file_name;
		switch($info['type']){
			case 'image/jpeg' :
				$image_source = imagecreatefromjpeg($info['tmp_name']);
				$result = imagejpeg($image_source, $file_full);
				break;
				
			case 'image/png' :
				$image_source = imagecreatefrompng($info['tmp_name']);
				$result = imagepng($image_source, $file_full);
				break;
				
			default :
				return $this->disposeJson(1, '该文件的类型不被支持');
				break;
		};
		if(false == $result){
			return $this->disposeJson(1, '保存图片失败');
		};
		
		$url_path = '/' . $dir_path . $file_name;
		return $this->disposeJson(0, '上传成功', array(
			'file_url' => str_replace('\\', '/', $url_path),
		));
	}
	
}